package com.cloud.form.api.service.impl;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.form.api.bean.FormFieldAuthorityBean;
import com.cloud.form.api.bean.FormFieldAuthorityEnum;
import com.cloud.form.api.entity.FormAssemblyInst;
import com.cloud.form.api.entity.FormDef;
import com.cloud.form.api.entity.FormFieldAuth;
import com.cloud.form.api.entity.FormAuth;
import com.cloud.form.api.mapper.FormAssemblyInstMapper;
import com.cloud.form.api.mapper.FormDefMapper;
import com.cloud.form.api.mapper.FormFieldAuthMapper;
import com.cloud.form.api.mapper.FormAuthMapper;
import com.cloud.form.api.service.FormAuthorityService;
import com.cloud.form.common.utils.SessionHelper;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class FormAuthorityServiceImpl implements FormAuthorityService {

	@Autowired
	private FormDefMapper formDefMapper;

	@Autowired
	private FormAssemblyInstMapper formAssemblyInstMapper;

	@Autowired
	private FormAuthMapper formInputAuthMapper;

	@Autowired
	private FormFieldAuthMapper formFieldAuthMapper;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Override
	public List<FormFieldAuthorityBean> listFormFields(long procDefId) {
		List<FormDef> formDef = formDefMapper.listFormByProc(procDefId);
		// 查找所有需要进行授权的表单组件
		List<FormAssemblyInst> formAssemblyInsts = formAssemblyInstMapper.listFormFieldsByProc(procDefId);
		List<FormFieldAuthorityBean> auths = new ArrayList<FormFieldAuthorityBean>(formDef.size());
		for (FormDef form : formDef) {
			FormFieldAuthorityBean formBean = new FormFieldAuthorityBean();
			formBean.setId(form.getFormId());
			formBean.setName(form.getFormName());
			for (FormAssemblyInst assembly : formAssemblyInsts) {
				if (assembly.getFormId().equals(form.getFormId())) {
					FormFieldAuthorityBean fieldBean = new FormFieldAuthorityBean();
					fieldBean.setId(assembly.getId());
					fieldBean.setName(assembly.getAssemblyName());
					fieldBean.setSeniorId(form.getFormId());
					formBean.getFields().add(fieldBean);
				}
			}
			auths.add(formBean);
		}
		return auths;
	}

	@Override
	public List<FormFieldAuthorityBean> loadFormFieldAuth(long actDefId, long partId) {
		List<FormAuth> inputAuth = null;
		List<FormFieldAuth> fieldAuth = null;
		if (partId > 0) {
			// 优先取细化到参与者的权限
			Example example = new Example(FormAuth.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("actDefId", actDefId);
			criteria.andEqualTo("partId", partId);
			inputAuth = formInputAuthMapper.selectByExample(example);
			fieldAuth = formFieldAuthMapper.listFieldByFormPart(actDefId, partId);
		} else {
			// 没找到，取对应的环节权限
			Example example = new Example(FormAuth.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("actDefId", actDefId);
			criteria.andEqualTo("partId", 0);
			inputAuth = formInputAuthMapper.selectByExample(example);
			fieldAuth = formFieldAuthMapper.listFieldByFormPart(actDefId, 0);
		}
		List<FormFieldAuthorityBean> auths = new ArrayList<FormFieldAuthorityBean>();
		for (FormAuth inputForm : inputAuth) {
			FormFieldAuthorityBean formBean = new FormFieldAuthorityBean();
			formBean.setId(inputForm.getFormId());
			if (inputForm.getAuthCode() > 0)
				formBean.setRead(1);
			for (FormFieldAuth inputFiled : fieldAuth) {
				FormFieldAuthorityBean fieldBean = new FormFieldAuthorityBean();
				fieldBean.setId(inputFiled.getFieldId());
				if (FormFieldAuthorityEnum.READ.getCode() == inputFiled.getAuthCode()) {
					fieldBean.setRead(1);
				} else if (FormFieldAuthorityEnum.WRITE.getCode() == inputFiled.getAuthCode()) {
					fieldBean.setWrite(1);
				}
				fieldBean.setSeniorId(formBean.getId());
				formBean.getFields().add(fieldBean);
			}
			auths.add(formBean);
		}
		return auths;
	}

	@Override
	public void saveFormFieldAuth(List<FormFieldAuthorityBean> auths, final long actDefId, long partId) {
		// 直接在环节上保存权限
		// 删当前参与者的权限，保存新的数据
		Example formExample = new Example(FormAuth.class);
		Example.Criteria criteria = formExample.createCriteria();
		criteria.andEqualTo("partId", partId);
		criteria.andEqualTo("actDefId", actDefId);
		formInputAuthMapper.deleteByExample(formExample);
		// 删除全部不可见表单的字段权限配置
		Example fieldExample = new Example(FormFieldAuth.class);
		Example.Criteria fieldCriteria = fieldExample.createCriteria();
		fieldCriteria.andEqualTo("partId", partId);
		fieldCriteria.andEqualTo("actDefId", actDefId);
		formFieldAuthMapper.deleteByExample(fieldExample);
		// 保存表单可见
		List<FormAuth> formAuth = new ArrayList<FormAuth>();
		List<FormFieldAuth> fieldsAuth = new ArrayList<FormFieldAuth>();
		for (FormFieldAuthorityBean form : auths) {
			if (form.getRead() > 0) {
				FormAuth inputFormAuth = new FormAuth();
				inputFormAuth.setFormId(form.getId());
				inputFormAuth.setActDefId(actDefId);
				inputFormAuth.setPartId(partId);
				inputFormAuth.setAuthCode(form.getRead());
				formAuth.add(inputFormAuth);
				List<FormFieldAuthorityBean> fields = form.getFields();
				for (FormFieldAuthorityBean field : fields) {
					if (field.getRead() > 0 || field.getWrite() > 0) {
						FormFieldAuth formFieldAuth = new FormFieldAuth();
						formFieldAuth.setFieldId(field.getId());
						formFieldAuth.setFormId(form.getId());
						formFieldAuth.setPartId(partId);
						int authCode = 0;
						if (field.getRead() == 1) {
							authCode = 1;
						} else if (field.getWrite() == 1) {
							authCode = 2;
						}
						formFieldAuth.setAuthCode(authCode);
						fieldsAuth.add(formFieldAuth);
					}
				}
			}
		}
		// 批量保存文书权限数据信息
		final List<FormAuth> form = formAuth;
		jdbcTemplate.batchUpdate(
				"insert into form_input_auth (act_def_id, part_id, form_id, auth_code) values (?, ?, ?, ?)",
				new BatchPreparedStatementSetter() {
					@Override
					public void setValues(PreparedStatement ps, int i) throws SQLException {
						FormAuth fia = form.get(i);
						ps.setLong(1, fia.getActDefId());
						ps.setLong(2, fia.getPartId());
						ps.setLong(3, fia.getFormId());
						ps.setInt(4, fia.getAuthCode());
					}

					@Override
					public int getBatchSize() {
						return form.size();
					}
				});
		// 批量保存字段权限数据信息
		final List<FormFieldAuth> field = fieldsAuth;
		jdbcTemplate.batchUpdate(
				"insert into form_field_auth (act_def_id, field_id, form_id, part_id, auth_code) values (?, ?, ?, ?, ?)",
				new BatchPreparedStatementSetter() {
					@Override
					public void setValues(PreparedStatement ps, int i) throws SQLException {
						FormFieldAuth ffa = field.get(i);
						ps.setLong(1, actDefId);
						ps.setLong(2, ffa.getFieldId());
						ps.setLong(3, ffa.getFormId());
						ps.setLong(4, ffa.getPartId());
						ps.setInt(5, ffa.getAuthCode());
					}

					@Override
					public int getBatchSize() {
						return field.size();
					}
				});
	}

	@Override
	public List<FormFieldAuth> loadFormActFieldAuth(long formId, long actDefId) {
		return formFieldAuthMapper.listFieldByFormActParts(formId, actDefId, SessionHelper.get().getParts());
	}

}
